/*
 * @(#)UserServiceImpl.java 2011
 *
 * Copyright 2011 classic-commerce
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package ca.ioniq.server.service.impl;

import javax.inject.Inject;

import org.apache.commons.beanutils.BeanUtils;

import ca.ioniq.server.dao.UserDAO;
import ca.ioniq.server.service.UserService;
import ca.ioniq.server.service.exception.UserException;
import ca.ioniq.server.service.security.EncodingService;
import ca.ioniq.shared.entity.Credential;
import ca.ioniq.shared.entity.User;

import com.google.inject.persist.Transactional;

/**
 * @author: <a href="mailto:richard@ioniq.ca">Richard Mutezintare</a>
 */
public class UserServiceImpl implements UserService {
	
    private UserDAO userDao;
    EncodingService encoder = new EncodingService();
	
	@Inject
	public UserServiceImpl(UserDAO userDao) {
		this.userDao = userDao;
	}

	@Transactional
	public User register(User user) {
    	Credential credential = encoder.getCredentialFromClearPassword(user.getCredential().getPassword());
        user.setCredential(credential);
    	userDao.persist(user);
		return user;
	}

	@Transactional
	public User changePassword(User user, String newPassword) {
		userDao.updatePassword(user, newPassword);
		return user;
	}

	@Transactional
	public User login(User user) { 
		return userDao.findByName(user.getUserName());
	}

	@Transactional
	public User update(User user) throws UserException {
		try {
			Long currentId = user.getId();
			User currentUser = userDao.findById(user.getId());
			BeanUtils.copyProperties(currentUser, user);
			currentUser.setId(currentId);
			
			return userDao.merge(currentUser);
		} catch (Exception e) {
			throw new UserException("Cannot update this user; maybe is not in the repository", e);
		}
	}

	@Transactional
	public User findUser(Long id) {
		return userDao.findById(id);
	}

	@Transactional
	public void deleteUser(Long id) throws UserException {
		try {
			User deletedUser = findUser(id);
			userDao.delete(deletedUser);
		} catch (Exception e) {
			throw new UserException("Cannot delete this user; maybe is not in the repository", e);
		}
	}
}
